package cn.uncode.baas.server.internal.context;

import org.apache.commons.lang3.StringUtils;
import cn.uncode.dal.cache.CacheManager;
import cn.uncode.baas.server.acl.token.AccessToken;
import cn.uncode.baas.server.utils.WebApplicationContextUtil;


public class RestContextManager {
	
	private static final ThreadLocal<RestContext> REST_CONTEXT = new ThreadLocal<RestContext>();
	
	public static void setContext(RestContext context) {
		REST_CONTEXT.set(context);
	}

	public static RestContext getContext() {
		if(REST_CONTEXT.get() == null){
			return new RestContext();
		}
		return REST_CONTEXT.get();
	}
	
	public static void initBucket(String bucket){
		RestContext context = REST_CONTEXT.get();
		if(null == context){
			context = new RestContext();
		}
		if(StringUtils.isNotBlank(bucket))
			context.setBucket(bucket);
		REST_CONTEXT.set(context);
	}
	
	public static void initAccessToken(String token){
		RestContext context = REST_CONTEXT.get();
		if(null == context){
			context = new RestContext();
		}
		if(StringUtils.isNotBlank(token)){
			CacheManager cacheManager = WebApplicationContextUtil.getBean("cacheManager", CacheManager.class);
			if(null != cacheManager && null != cacheManager.getCache()){
				AccessToken accessToken = (AccessToken) cacheManager.getCache().getObject(token);
				if(accessToken != null && !accessToken.isExpired()){
					context.setToken(accessToken);
				}
			}
		}
		REST_CONTEXT.set(context);
	}
	
	public static void clearContext(){
		REST_CONTEXT.remove();
	}

	
	

}
